import router from 'koa-router';
import RSATool from '../lib/RSATool';
import configTool from '../com/configTool';
import getServerInfo from '../lib/System/getServerInfo';


const AuthorizeRoutes = new router({prefix: '/AuthorizeServer'});

AuthorizeRoutes
    .get('/login', async (ctx: any) => {
        let {userName, password} = ctx.request.query;

        const userInfo = configTool.baseConfig.userList.find((item: any) => item.userName === userName && item.password === password);
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        if (userInfo) {
            const serverInfo = getServerInfo();
            const userCopy: any = {...userInfo};

            delete userCopy.password;
            userCopy.ip = ctx.request.ip;
            userCopy.token_expired_date = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 7).toISOString();
            userCopy.token = RSATool.encrypt(JSON.stringify(userCopy), configTool.baseConfig.publicDer);

            ctx.body = JSON.stringify({
                code: 200,
                message: '登录成功',
                data: {serverInfo, userInfo: userCopy}
            });
            ctx.status = 200;
        } else {
            ctx.body = JSON.stringify({
                code: 401,
                message: '登录失败，用户名或密码错误',
                data: null
            });
            ctx.status = 401;
        }
    })

export default AuthorizeRoutes;
